//
//  KCNetworkManager.swift
//  MyKC
//
//  Created by yy on 2017/1/19.
//  Copyright © 2017年 com.yasuo. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
//这种声明枚举的方式没有原始值
enum HTTPMethod {
    case POST
    case GET
}

class KCNetworkManager: AFHTTPSessionManager {
    //封装get和set方法
    //声明单例对象
    
    static let sharedTools:KCNetworkManager = {
        let tools = KCNetworkManager()
//        tools.requestSerializer.value(forHTTPHeaderField: <#T##String#>)
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // MARK:  设置接收的数据类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/html") as? Set<String>
        
        let info: NSDictionary = Bundle.main.infoDictionary! as NSDictionary
        let app_version = info.object(forKey: "CFBundleShortVersionString")!
        let device = UIDevice.init()
        let systemVersion = device.systemVersion
        let model = device.model
        
        tools.requestSerializer.setValue(shareAppSetting.accessToken, forHTTPHeaderField: "AccessToken")
        
        if shareAppSetting.userType == "5000450" || shareAppSetting.userType == "5000410" {
            tools.requestSerializer.setValue(shareAppSetting.storeId, forHTTPHeaderField: "StoreId")
        }
        
//        tools.requestSerializer.setValue(, forHTTPHeaderField: @"User-Agent")
        return tools
    }()
    
    static let defaultTools:KCNetworkManager = {
        let tools = KCNetworkManager()
        return tools
    }()
    
    
    //封装核心方法
    func request(method: HTTPMethod, urlString: String, parameters: Any?, finished: @escaping (Any?,Error?) -> ()) {
        let port = "http://139.129.207.164:8004" + urlString
        //提前定义失败和成功的闭包 将闭包当做参数传递
        //成功的回调
        let successCallBack = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //这里需要使用到参数
            let dic = responseObject as! NSDictionary
            let status = Int((dic["Status"]! as! NSNumber))
            // MARK: -  这个地方崩溃了  因为传递的msg是null
            let msg = dic["Msg"]! as? String
            if(status == 200){
                finished(dic, nil)
            }
            else if(status == 403) {
                let loginVC = KCLoginViewController()
                SVProgressHUD.setMinimumDismissTimeInterval(1)
                SVProgressHUD.showError(withStatus: msg)
                UIApplication.shared.keyWindow?.rootViewController = loginVC
//                finished(dic, nil)
            }
            else {
                SVProgressHUD.setMinimumDismissTimeInterval(1)
                SVProgressHUD.showError(withStatus: msg)
            }
        }
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
//            print(error)
            finished(nil, error)
//            self.afnetWorkingErrorMessge(errorMessge: error as NSError)
        }
        if method == .GET {
            get(port, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            post(port, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
    
    // MARK:  登录方法的封装------这个成功后需要存储token
    func loginRequest(para:[String : String], response: @escaping (Any?,Error?) -> ()) {
        let manager = AFHTTPSessionManager.init()
        manager.requestSerializer.timeoutInterval = 60
        let port = "http://139.129.207.164:8004"
        let loginString = "/api/Authorize/SignIn"
        let kloginStr = port + loginString
        // MARK:  如果是不需要存储token的信息的话就直接调用这个方法就好了------------
        manager.post(kloginStr, parameters: para, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
            //这里需要使用到参数
//            print(responseObject ?? [String: String])
            let dic = responseObject as! [String: Any]
            let status = Int((dic["Status"]! as! NSNumber))
            let msg = dic["Msg"]! as! String
            if(status == 200){
                response(dic, nil)
            }
            else if(status == 403) {
                let loginVC = Bundle.main.loadNibNamed("KCLoginViewController", owner: nil, options: [:])?.last as! KCLoginViewController
                UIApplication.shared.keyWindow?.rootViewController = loginVC
                response(dic, nil)
            }
            else {
                SVProgressHUD.setMinimumDismissTimeInterval(1)
                SVProgressHUD.showError(withStatus: msg)
            }
        }) { (task: URLSessionDataTask?, error: Error) in
            SVProgressHUD.show(withStatus: error.localizedDescription)
            response(nil, error)
            let er = error as NSError
            self.afnetWorkingErrorMessge(errorMessge: er)
        }
    }
    
    // MARK: -  封装上传图片的方法---这个是封装的问卷地方的图片上传------------
//    func request(method: HTTPMethod, urlString: String, parameters: Any?, finished: @escaping (Any?,Error?) -> ())
    func upload(urlString: String, parameters: Any?, imageAllArray: [KCQuestionModel]?, finished: @escaping (Any?,Error?)->()) {
        let port = "http://139.129.207.164:8004" + urlString
        //提前定义失败和成功的闭包 将闭包当做参数传递
        //成功的回调
        let successCallBack = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //这里需要使用到参数
            let dic = responseObject as! NSDictionary
            let status = Int((dic["Status"]! as! NSNumber))
            // MARK: -  这个地方崩溃了  因为传递的msg是null
            let msg = dic["Msg"]! as? String
            if(status == 200){
                finished(dic, nil)
            }
            else if(status == 403) {
                let loginVC = KCLoginViewController()
                SVProgressHUD.setMinimumDismissTimeInterval(1)
                SVProgressHUD.showError(withStatus: msg)
                UIApplication.shared.keyWindow?.rootViewController = loginVC
            }
            else {
                SVProgressHUD.setMinimumDismissTimeInterval(1)
                SVProgressHUD.showError(withStatus: msg)
            }
        }
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
            finished(nil, error)
        }
        post(port,parameters: parameters,constructingBodyWith: { (formData) in
            for (imageEnumArrayModel) in imageAllArray! {
                if imageEnumArrayModel.QuestionType == "800003" {
                    let name = "Photos_" + imageEnumArrayModel.QuestionId!
                    for image in imageEnumArrayModel.imageArray! {
                        let data = UIImagePNGRepresentation(image)
                        formData.appendPart(withFileData: data!, name: name, fileName: "1.jpg", mimeType: "image/jpeg")
                    }
                }
            }
        }, progress: nil,
           success: successCallBack,
           failure: failureCallBack)
    }
    
    
    
    // MARK:  登录失败的信息描述-------有新的方法吗?-----------------
    func afnetWorkingErrorMessge(errorMessge: NSError){
        switch errorMessge.code {
        case NSFileReadUnknownError | NSFileWriteUnknownError:
            SVProgressHUD.show(withStatus: "未知问题")
            break
        case NSFileReadNoPermissionError | NSFileWriteNoPermissionError:
            SVProgressHUD.show(withStatus: "权限问题")
            break
        case NSFileReadTooLargeError:
            SVProgressHUD.show(withStatus: "文件太大")
            break
        case NSFileReadInvalidFileNameError:
            SVProgressHUD.show(withStatus: "无效的文件名")
            break
//        case NSURLErrorNotConnectedToInternet | NSURLErrorCannotConnectToHost |:
//            SVProgressHUD.show(withStatus: "无法连接到服务器")
//            break
        case NSURLErrorTimedOut:
            SVProgressHUD.show(withStatus: "请求超时")
            break
        case NSURLErrorBadServerResponse:
            SVProgressHUD.show(withStatus: "无响应")
            break
        default:
            SVProgressHUD.show(withStatus: "请检查您的网络")
            break
        }
    }
}
